package com.zyw.conf;

import com.zyw.filter.LxbCorsFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

/**
 * <p>跨域访问设置</p>
 * <p>在开发阶段联调使用，测试/生产环境，可用Nginx代理设置，无需此类配置</p>
 */
@Configuration
public class CorsConfig {
	
	@Bean
	public LxbCorsFilter corsFilter() {
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		source.registerCorsConfiguration("/**", buildCorsCofing());
		return new LxbCorsFilter(source);
	}
	
	private CorsConfiguration buildCorsCofing() {
		CorsConfiguration corsConfiguration = new CorsConfiguration();
		corsConfiguration.addAllowedOrigin("*");
		corsConfiguration.addAllowedHeader("*");
		corsConfiguration.addAllowedMethod("*");
		return corsConfiguration;
	}
	
	@Bean
	@Order(Ordered.HIGHEST_PRECEDENCE)
	public FilterRegistrationBean crosFilterRegistrationBean() {
		FilterRegistrationBean crosFilterRegBean = new FilterRegistrationBean();
		crosFilterRegBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
		crosFilterRegBean.setFilter(corsFilter());
		crosFilterRegBean.addUrlPatterns("/*");
		crosFilterRegBean.setName("crosFilter");
		return crosFilterRegBean;
	}
	
}
